package com.zhongxi.guoyuan.view.play;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.gift.MoneyTreeResult;
import com.zhongxi.guoyuan.entity.gift.ShareBeautifulResult;
import com.zhongxi.guoyuan.entity.gift.ShareResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.MyTextUtils;
import com.zhongxi.guoyuan.view.MainActivity;
import com.zhongxi.guoyuan.view.NewTipsActivity;
import com.zhongxi.guoyuan.view.personalCenter.BoxActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.shaketree.controller.MainContract;
import com.zhongxi.guoyuan.widget.shaketree.controller.MainModleImp;
import com.zhongxi.guoyuan.widget.shaketree.controller.MainPresentorImp;
import com.zhongxi.guoyuan.widget.shaketree.widget.FlakeView;

import org.json.JSONObject;

import pl.droidsonroids.gif.GifImageView;

public class MoneyTreeActivity extends BaseActivity implements MainContract.MainView{

    private GifImageView gif;
    private RelativeLayout container;
    private ImageView image;
    private MainPresentorImp mainPresentorImp;
    private ObjectAnimator objectAnimator;
    private FlakeView flakeView;

    private boolean show = false;
    private MainModleImp mainModleImp;

    private boolean type;
    private TextView tvChange;
    private TextView tvTodayGold;
    private String flag;
    private MoneyTreeResult result;
    private TextView tvDetail;
    private TextView tvGold;
    private ImageView ivTips;
    private PopupWindow popupWindow;
    private View popupWindow_view;
    private TextView tvShare;
    private SHARE_MEDIA platform;
    private UMShareAPI mShareAPI;
    public static final int resultMeiBiCode=100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_money_tree);
        initTitle();
        mShareAPI = UMShareAPI.get(this);
        container = (RelativeLayout) findViewById(R.id.rela);
        image = (ImageView) findViewById(R.id.ivImg);
        ivTips = (ImageView)findViewById(R.id.ivTips);

        tvChange = (TextView) findViewById(R.id.tvChange);
        tvTodayGold = (TextView) findViewById(R.id.tvTodayGold);
        tvGold = (TextView) findViewById(R.id.tvGold);
        tvDetail = (TextView) findViewById(R.id.tvDetail);
        //查看详情
        tvDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(BoxActivity.class);
            }
        });
        tvGold.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("index",0);
                startActivity(intent);
            }
        });
        ivTips.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAct(NewTipsActivity.class);
            }
        });

        if(!MyTextUtils.isFastDoubleClick()){
            flag ="info";
            getServer(Url.SHAKE_INNER, null,"", false, null, "get");
        }

        tvTitle.setText("美币摇钱树");
        mainPresentorImp = new MainPresentorImp();
        mainModleImp = new MainModleImp(mainPresentorImp.handler, this);
        mainPresentorImp.setMainView(this);
        mainPresentorImp.setMainModle(mainModleImp);
        //启动重力传感器
        mainPresentorImp.shake();
        //摇一摇的动画
        objectAnimator = ObjectAnimator.ofFloat(image, "Rotation", 0,60,0,-60,0,60,0,-60).setDuration(2000);
		/*flakeView = new FlakeView(this);*/

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            result = gson.fromJson(response, MoneyTreeResult.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj()))
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            if("info".equals(flag)){
                initInfo(result);
            }else if("receiver".equals(flag)){
                initInfo(result);
                showPopupWindow(result.getRecive());
            }else if("share".equals(flag)){
                ShareResult result = gson.fromJson(response, ShareResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                //分享
                if (null != popupWindow && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    initPopuWindow(result);
                }
            }else if("shareget".equals(flag)){
                ShareBeautifulResult result = gson.fromJson(response, ShareBeautifulResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                showPopupWindow(result.getNum(), "分享");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void showPopupWindow(String num, String str) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_share, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);

        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvTips.setText("成功分享获得"+num+"个美币");
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                setResult(resultMeiBiCode);
                finish();
            }
        });
    }

    /**
     * 弹出分享界面
     * @param result
     */
    private void initPopuWindow(final ShareResult result) {
        popupWindow_view = getLayoutInflater().inflate(R.layout.pop_shared, null, false);
        popupWindow = new PopupWindow(popupWindow_view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0xb0000000));
        popupWindow.setFocusable(true);
        popupWindow.showAtLocation(container, Gravity.BOTTOM, 0, 0);
        TextView tv_cancle = (TextView) popupWindow_view.findViewById(R.id.tv_cancle);
        LinearLayout ll_qq = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qq);
        LinearLayout ll_wechat = (LinearLayout) popupWindow_view.findViewById(R.id.ll_wechat);
//        LinearLayout ll_microblog = (LinearLayout) popupWindow_view.findViewById(R.id.ll_microblog);
        LinearLayout ll_qzone = (LinearLayout) popupWindow_view.findViewById(R.id.ll_qzone);
        LinearLayout ll_friendscircle = (LinearLayout) popupWindow_view.findViewById(R.id.ll_friendscircle);
        View.OnClickListener shareClickListener = new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.ll_qq:
                        platform = SHARE_MEDIA.QQ;
                        break;
                    case R.id.ll_wechat:
                        platform = SHARE_MEDIA.WEIXIN;
                        break;
                    case R.id.ll_qzone:
                        platform = SHARE_MEDIA.QZONE;
                        break;
                    case R.id.ll_friendscircle:
                        platform = SHARE_MEDIA.WEIXIN_CIRCLE;
                        break;
                }
                new ShareAction(MoneyTreeActivity.this).setPlatform(platform).setCallback(umShareListener).withTitle("美容何必再花钱！消费多少返多少=免费美容！")
                        .withText("手机里装一个自己的美容院，天天“摇钱树+搜红包”消费返银币=实现免费美容，下载即送大礼包！").withTargetUrl(Url.BASE_URL+"/share/welfare/show?sharekey="+result.getSharekey())
                        .share();
                popupWindow.dismiss();
            }
        };
        ll_qq.setOnClickListener(shareClickListener);
        ll_wechat.setOnClickListener(shareClickListener);
        ll_qzone.setOnClickListener(shareClickListener);
        ll_friendscircle.setOnClickListener(shareClickListener);
        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.i("base", "result");
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                showShortToast("收藏成功啦");
            } else {
                showShortToast("分享成功啦");
            }
            flag = "shareget";
            getServer(Url.SHARE, null, "", false, null, "get");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("base", "fail");
            showShortToast("分享失败啦");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Log.i("base", "cancel");
            showShortToast("分享取消了");
        }
    };

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if(result.getCode() == 1001){
                    /*showShortToast("用户未登录,请先登录");
                    Intent intent = new Intent (context, LoginActivity.class);
                    startActivityForResult(intent, 300);*/
                    startAct(LoginActivity.class);
                    finish();
                }else if(result.getCode()==1101){
                    try {
                        JSONObject obj = new JSONObject(response);
                        String residualCount = obj.getString("residualCount");
                        String totalFee = obj.getString("totalFee");
                        if (null != residualCount && !"".equals(residualCount)) {
                            tvChange.setText("今日您还有 " + residualCount + " 次摇美币的机会");
                        } else {
                            tvChange.setText("今日您还有 * 次摇美币的机会");
                        }
                        if (null != totalFee && !"".equals(totalFee)) {
                            tvTodayGold.setText("今日累积获得美币 " + totalFee + " 枚");
                        }
                        showShortToast("摇美币次数已超限");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else if(result.getCode() == 1103){
                    showShortToast("已达最大日限额");
                    finish();
                }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化数据
     * @param result
     */
    private void initInfo(MoneyTreeResult result) {
        if(null!=result.getResidualCount()&&!"".equals(result.getResidualCount())){
            tvChange.setText("今日您还有 "+result.getResidualCount()+" 次摇美币的机会");
        }else{
            tvChange.setText("今日您还有 * 次摇美币的机会");
        }
        if(null!=result.getTotalFee()&&!"".equals(result.getTotalFee())){
            tvTodayGold.setText("今日累积获得美币 "+result.getTotalFee()+" 枚");
        }
    }

    @Override
    public void onShake(boolean flage) {
        if(flage&&!type&&!MyTextUtils.isFastDoubleClick()){
            flakeView = new FlakeView(this);
            container.addView(flakeView);
            //设置背景
            this.getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));
            //设置同时出现在屏幕上的金币数量 建议64以内 过多会引起卡顿
            flakeView.addFlakes(8);

            /**
             * 绘制的类型
             * @see View.LAYER_TYPE_HARDWARE
             * @see View.LAYER_TYPE_SOFTWARE
             * @see View.LAYER_TYPE_NONE
             */
            flakeView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

            /**
             * 移除动画
             */
            final Thread thread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        //设置2秒后
                        Thread.sleep(2000);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                container.removeAllViews();
                                show = false;
                                flag = "receiver";
                                getServer(Url.SHAKE_INNER_RECIVE, null, "", false, null, "get");
                            }
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            if(!show){
                thread.start();
                show = true;
            }
            MediaPlayer player = MediaPlayer.create(this, R.raw.shake);
            player.start();
        }
    }

    private void showPopupWindow(String recive) {
        type = true;
        mainPresentorImp.onDestroy();
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_gold, null);
        final PopupWindow pw = new PopupWindow(contentView, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT,true);

        //分享
        tvShare = (TextView) contentView.findViewById(R.id.tvShare);
        tvShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                flag = "share";
                String str = "&sharetype=1";
                getServer(Url.APPLY_SHARE, null, str, false, null, "get");
                pw.dismiss();
            }
        });

        TextView tvMeibi = (TextView) contentView.findViewById(R.id.tvMeibi);
        tvMeibi.setText("美币"+recive+"个");

        TextView tvBack = (TextView) contentView.findViewById(R.id.tvBack);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pw.dismiss();
                mainPresentorImp = new MainPresentorImp();
                mainPresentorImp.setMainModle(mainModleImp);
                //启动重力传感器
                mainPresentorImp.shake();
            }
        });
        pw.setTouchable(true);
        pw.setFocusable(true);
        backgroundAlpha(0.3f);
        pw.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                type = false;
            }
        });
        pw.showAtLocation(container, Gravity.CENTER, 0, 0);
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(flakeView!= null)
            flakeView.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        setResult(resultMeiBiCode);
        if(flakeView!= null)
            flakeView.pause();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mainModleImp.onDestory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainModleImp.onDestory();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }
}
